package guild

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/os/gmlock"
	"sort"
	"xr-game-server/core/constants/cmd"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/httpserver"
	"xr-game-server/core/push"
	"xr-game-server/dao/guilddao"
	"xr-game-server/dao/roledao"
	"xr-game-server/dto/guilddto"
	"xr-game-server/entity"
	"xr-game-server/errercode"
)

// TransferGuild 转让公会会长
func TransferGuild(ctx context.Context, reqData *guilddto.GuildTransferReq) (bool, error) {
	// 获取当前用户角色
	// 获取当前用户角色
	roleId := httpserver.GetAuthId(ctx)
	roleData := roledao.GetRoleByRole(roleId)

	if roleData.GuildId == common.Zero {
		return false, errercode.CreateCode(errercode.GuildNonExist)
	}
	lockKey := fmt.Sprintf(GuildLock, roleData.GuildId)
	defer gmlock.Unlock(lockKey)
	lockFlag := gmlock.TryLock(lockKey)
	if !lockFlag {
		return false, errercode.CreateCode(errercode.SysBuyLimit)
	}
	//检查权限
	memberData := guilddao.GetMemberByRoleId(roleData.GuildId, roleId)
	if memberData.Title == entity.GuildMemberTitleMember {
		//普通成员不可以审批
		return false, errercode.CreateCode(errercode.NoPermission)
	}

	targetMember := guilddao.GetMemberByRoleId(roleData.GuildId, reqData.NewOwnerId)
	//检查是否在同个工会
	if targetMember.GuildId != roleData.GuildId {
		return false, errercode.CreateCode(errercode.NoPermission)
	}
	targetMember.SetTitle(entity.GuildMemberTitlePresident)

	memberData.SetIsDeleted(true)
	//重置本人公会长
	roleData.SetGuildId(common.Zero)
	guilddao.DelMember(targetMember.GuildId, roleId)

	//工会成员列表刷新
	members := guilddao.GetGuildMembers(targetMember.GuildId)
	sort.Sort(MemberByUpdateAt(members))
	for _, val := range members {
		push.OutData(val.RoleId, cmd.FlushGuildMember)
	}
	return true, nil
}
